// pages/qr/to.js
const App = getApp()
import Kits from '../../utils/kits'

Page({
  data: {
    init: false,
    url: ''
  },
  onLoad(options) {
    this.waitForReady(options)
  },
  waitForReady(options) {
    if (App.Global.OpenId) {
      this.goto(options)
    } else {
      setTimeout(() => {
        this.waitForReady(options)
      }, 200);
    }
  },
  goto(options) {
    let ourl = decodeURIComponent(options.q)
    this.setData({
      init: true,
      url: ourl
    })
    console.log(ourl)
    let t = ourl.split('?')[1].split('&')[0].split('=')[1]
    console.log(t)

    let auth = false
    let refer = {}
    let uri = ''
    if (t === 'oc') {
      // "/to/c?t=oc&tag=" + tag + "&mch=" + mchId + "&clk=" + clkId
      let tag = ourl.split('?')[1].split('&')[1].split('=')[1]
      let mch = ourl.split('?')[1].split('&')[2].split('=')[1]
      let clk = ourl.split('?')[1].split('&')[3].split('=')[1]
      uri = `/pages/order/create?tag=${tag}&back=false`
      auth = true
      refer = {
        mch: mch,
        clk: clk
      }
    } else if (t === 'ci') {
      // "/to/c?t=ci&car=" + carId + "&mch=" + mchId + "&clk=" + clkId
      let car = ourl.split('?')[1].split('&')[1].split('=')[1]
      let mch = ourl.split('?')[1].split('&')[2].split('=')[1]
      let clk = ourl.split('?')[1].split('&')[3].split('=')[1]
      let now = Kits.getNextTime(new Date().getTime())
      uri = `/pages/order/create?carid=${car}&clk=${clk}&begin=${now.getTime()}&close=${now.addDays(2).getTime()}&onsite=&onsite_area=&onsite_locs=&onsite_addr=&back=false`
      auth = true
      refer = {
        mch: mch,
        clk: clk
      }
    } else if (t === 'mi') {
      // "/to/c?t=mi&mch=" + mchId + "&clk=" + clkId
      let mch = ourl.split('?')[1].split('&')[1].split('=')[1]
      let clk = ourl.split('?')[1].split('&')[2].split('=')[1]
      uri = `/pages/home/mcar?mchid=${mch}&clkid=${clk}`
      auth = true
      refer = {
        mch: mch,
        clk: clk
      }
    }

    if (auth && !App.Global.User.id) {
      // 未登录情况
      wx.redirectTo({
        url: `/pages/user/login?back=false&next=${encodeURIComponent(uri)}&refer=${JSON.stringify(refer)}`,
      })
    } else {
      wx.redirectTo({
        url: uri
      })
    }


  },
})